package com.ws.gc.web.auth.handler;

import com.ws.rain.base.result.R;
import com.ws.rain.base.result.ResultCode;
import com.ws.rain.base.utils.character.CharEncode;
import com.ws.rain.base.utils.json.JsonUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.io.UnsupportedEncodingException;

@Component
public class CustomAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");
        String body = JsonUtil.toJson(R.fail(ResultCode.UN_AUTHORIZED,"请登录"));
        try {
            DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(CharEncode.UTF_8));
            return response.writeWith(Mono.just(buffer));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
